package com.xjl.common.redis.init;

import com.xjl.common.redis.context.SpringContextUtil;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class InitCache implements CommandLineRunner {

    /**
     * 项目启动的时候 run ....
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        //进行缓存预热
        //调用Spring容器中所有继承Abstract子类的initCache方法
        //首先从容器中获取所有Abstract子类
        ApplicationContext applicationContext = SpringContextUtil.getApplicationContext();
        Map<String, AbstractCache> beansOfType = applicationContext.getBeansOfType(AbstractCache.class);

        //调用init方法
        if(beansOfType.isEmpty()) return;
        for(Map.Entry<String,AbstractCache> entry: beansOfType.entrySet()){
            AbstractCache bean = (AbstractCache) SpringContextUtil.getBean(entry.getValue().getClass());
            bean.initCache();
        }
    }
}
